﻿using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using Newtonsoft.Json;

namespace Components
{
    /// <summary>
    /// Json处理类
    /// </summary>
    public class Json
    {
        /// <summary>
        /// 将一个对象序列化成JSON字符串
        /// </summary>
        /// <param name="obj">待序列化的对象</param>
        /// <returns>返回序列化后的JSON字符串</returns>
        /// <example>
        /// 测试JSON字符串的方法
        ///    var objPerson = new
        ///        {
        ///            Name = "Jack",
        ///            Age = 18,
        ///            Sex = "Man"
        ///        };
        ///    var retStr = Json.ConvertToString(objPerson);
        ///
        ///    Response.Write(retStr);
        ///    //{"Name":"Jack","Age":18,"Sex":"Man"}
        /// </example>
        public static string ToString(object obj)
        {
            if (obj == null)
                return null;

            return JavaScriptConvert.SerializeObject(obj);
        }

        /// <summary>
        /// 将DataTable转换成序列化成Json字符串
        /// </summary>
        /// <param name="dataTable">待操作DataTable</param>
        /// <returns>返回序列化后的Json字符串</returns>
        /// <example>
        /// //测试DataTable;
        ///     DataTable table = new DataTable();
        /// 
        ///     //创建列
        ///     DataColumn dc = new DataColumn("f1");
        ///     table.Columns.Add(dc);
        /// 
        ///     dc = new DataColumn("f2");
        ///     table.Columns.Add(dc);

        ///     DataRow dr = table.NewRow();
        ///     dr["f1"] = "Stone";
        ///     dr["f2"] = "18";
        /// 
        ///     table.Rows.Add(dr);

        ///     dr = table.NewRow();
        ///     dr["f1"] = "Stone";
        ///     dr["f2"] = "18";

        ///     table.Rows.Add(dr);

        ///     var str = Json.ConvertToString(table);
        ///     Response.Write(str);
        ///     //[{"f1":"Stone","f2":"18"},{"f1":"Stone","f2":"18"}] 
        /// </example>
        public static string ToString(DataTable dataTable)
        {
            return JavaScriptConvert.SerializeObject(dataTable, new DataTableConverter());
        }

        public static string ToStringZip(DataTable dataTable)
        {
            return StringUtil.Zip(ToString(dataTable));
        }

        public static DataTable ToTableUnZip(string stream)
        {
            string value = StringUtil.UnZip(stream);

            return ToObject<DataTable>(value);
        }

        /// <summary>
        /// 将字符串流转换成指定的对象
        /// </summary>
        /// <typeparam name="T">要转换的对象类型</typeparam>
        /// <param name="stream">字符串流</param>
        /// <returns>返回转换后的对象</returns>
        public static T ToObject<T>(string stream)
        {
            if (string.IsNullOrEmpty(stream))
                return default(T);

            T ret;

            try
            {
                if (typeof(T) == typeof(DataTable))
                {
                    ret = JavaScriptConvert.DeserializeObject<T>(stream, new DataTableConverter());
                }
                else
                {
                    ret = JavaScriptConvert.DeserializeObject<T>(stream);
                }
            }
            catch (Exception ex)
            {
                //ret = default(T);
                throw ex;
            }

            return ret;
        }

        /// <summary>
        /// 由于Json序列化DataTable会让类型信息丢失，用Xml可以解决此问题
        /// </summary>
        /// <param name="pDt"></param>
        /// <returns></returns>
        public static string TableToXml(DataTable pDt)
        {
            StringBuilder sb = new StringBuilder();
            XmlWriter writer = XmlWriter.Create(sb);
            XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
            serializer.Serialize(writer, pDt);
            writer.Close();
            return sb.ToString();
        }

        public static DataTable XmlToTable(string pXml)
        {
            StringReader strReader = new StringReader(pXml);
            XmlReader xmlReader = XmlReader.Create(strReader);
            XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
            DataTable dt = serializer.Deserialize(xmlReader) as DataTable;
            return dt;
        }
    }
}
